package com.ruoyi.system.service.impl;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TourismUserMapper;
import com.ruoyi.system.domain.TourismUser;
import com.ruoyi.system.service.ITourismUserService;

import javax.annotation.Resource;

/**
 * 用户Service业务层处理
 *
 * @author gqd
 * @date 2020-12-26
 */
@Service
@Slf4j
public class TourismUserServiceImpl implements ITourismUserService
{
    @Autowired
    private TourismUserMapper tourismUserMapper;
    @Resource
    private CommonMethod commonMethod;
    @Resource
    private DecodeUtils decodeUtils;
    @Resource
    private RedisClient redisClient;

    /**
     * 查询用户
     *
     * @param id 用户ID
     * @return 用户
     */
    @Override
    public TourismUser selectTourismUserById(Integer id)
    {
        return tourismUserMapper.selectTourismUserById(id);
    }

    /**
     * 查询用户列表
     *
     * @param tourismUser 用户
     * @return 用户
     */
    @Override
    public List<TourismUser> selectTourismUserList(TourismUser tourismUser)
    {
        return tourismUserMapper.selectTourismUserList(tourismUser);
    }

    /**
     * 新增用户
     *
     * @param tourismUser 用户
     * @return 结果
     */
    @Override
    public int insertTourismUser(TourismUser tourismUser)
    {
        tourismUser.setCreateTime(DateUtils.getNowDate());
        return tourismUserMapper.insertTourismUser(tourismUser);
    }

    /**
     * 修改用户
     *
     * @param tourismUser 用户
     * @return 结果
     */
    @Override
    public int updateTourismUser(TourismUser tourismUser)
    {
        tourismUser.setUpdateTime(DateUtils.getNowDate());
        return tourismUserMapper.updateTourismUser(tourismUser);
    }

    /**
     * 批量删除用户
     *
     * @param ids 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteTourismUserByIds(Integer[] ids)
    {
        return tourismUserMapper.deleteTourismUserByIds(ids);
    }

    /**
     * 删除用户信息
     *
     * @param id 用户ID
     * @return 结果
     */
    @Override
    public int deleteTourismUserById(Integer id)
    {
        return tourismUserMapper.deleteTourismUserById(id);
    }



    /**
     * 微信登录
     * @param
     * @return
     */
    /*@Override
    public AjaxResult userLogin(String avatarUrl,String nickName,Integer sex,String code) {
        Map<String, Object> resultMap = new HashMap<>(3);
        Map map = new HashMap();
        log.info("进入微信登录实现方法----------------->");
        String sexs = sex + "";
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        String url="https://api.weixin.qq.com/sns/jscode2session?appid=wx89103645693c94bf&secret=e1f52ca3a47b929325ea21857757af80&js_code="+code+"&grant_type=authorization_code";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解析json
        JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
        String sessionKeys = jsonObject.get("session_key").toString();
        log.info("sessionKey-------"+sessionKeys);
        String openId = jsonObject.get("openid").toString();
        //校验openId是否有效
        if (StringUtils.isBlank(openId) || StringUtils.isBlank(sessionKeys)) {
            return AjaxResult.error("微信登录失败！");
        }
        //以unionId去查是否存在用户,如果存在修改用户信息并返回
        TourismUser tourismUser = tourismUserMapper.selectUserByOpenId(openId);
        if (null != tourismUser) {
            tourismUser.setSessionKey(sessionKeys);
            tourismUserMapper.updateTourismUser(tourismUser);

//            if (1 == tourismUserMapper.updateUserSessionKey(sessionKeys,tourismUser.getId())) {
//                log.info("修改用户sessionKey成功----------->");
//            }
            String phone = tourismUser.getUserPhone();
            if (StringUtils.isNotBlank(phone)) {
                resultMap.put("phone", tourismUser.getUserPhone());
                //以userId作为redisKey存入redis并设置有效时间为半小时
                redisClient.set(tourismUser.getTourismId(), phone, 1800);
            }
            resultMap.put("resultCode", "1000");
            resultMap.put("resultMsg", "微信登录成功");
            resultMap.put("userInfo", tourismUser);
            return AjaxResult.success(resultMap);
        }
        //获取当前时间
        String localDateTime = commonMethod.getLocalDateTime("yyyyMMddHHmmss");
        //设置新增用户参数map
        String id = localDateTime + commonMethod.getuid(6);
        //下载微信头像并保存到本地
        *//*String fileName = "headImg" + id;
        commonMethod.downloadImg(avatarUrl, fileName, "F:\\image");
        String image = "F:\\image" + fileName + ".jpg";*//*
        TourismUser tourismUser1 = new TourismUser();
        tourismUser1.setNickName(nickName);
        tourismUser1.setUserPhoto(avatarUrl);
        tourismUser1.setUserSex(sexs);
        tourismUser1.setTourismId(openId);
        tourismUser1.setSessionKey(sessionKeys);
        map.put("headImg",avatarUrl);
        map.put("userInfo",tourismUser1);
        //新增用户信息
        if (1 == tourismUserMapper.insertTourismUser(tourismUser1)) {
            log.info("插入用户成功------------>");
            //设置返回值
            resultMap.put("user", map);
            return AjaxResult.success(resultMap);
        } else {
            return AjaxResult.error("微信登录失败,请稍后重试");
        }
    }*/

    /**
     * 解析手机号
     * @param encryptedData
     * @param iv
     * @param userId
     * @return
     */
    /*@Override
    public AjaxResult userDecodePhone(String encryptedData, String iv, Integer userId) {
        log.info("进入解密手机号实现方法------------->");
        //设置返回值
        Map map = new HashMap<>();
        try {
        //通过userId获取用户信息用于解密手机号
        TourismUser tourismUser = tourismUserMapper.selectByUserId(userId);
        if (null == tourismUser) {
            return AjaxResult.error("用户信息错误,请稍后重试");
        }
        if (StringUtils.isNotBlank(tourismUser.getUserPhone())) {
            //以userId作为redisKey存入redis并设置有效时间为半小时
            redisClient.set(tourismUser.getTourismId(), tourismUser.getUserPhone(), 1800);
            map.put("resultMsg", "获取用户手机号成功");
            map.put("tourismUser", tourismUser);
            return AjaxResult.success(map);
        }
        String sessionKey = tourismUser.getSessionKey();
        log.info("用于解密的sessionKey-------------->" + sessionKey);
        //解密获得手机号
            JSONObject decrypt = decodeUtils.decrypt(encryptedData, iv, sessionKey);
            String phone = decrypt.getString("phoneNumber");
            System.out.println(phone);

        if (StringUtils.isNotEmpty(phone)) {
            tourismUser.setUserPhone(phone);
            log.info("用户手机号为--------->" + phone);
            //插入用户手机号
            if (1 == tourismUserMapper.updateTourismUser(tourismUser)) {
                log.info("插入用户手机号成功----------->");
            } else {
                log.error("插入用户手机号失败----------->");
            }
            //以userId作为redisKey存入redis并设置有效时间为半小时
            redisClient.set(tourismUser.getTourismId(), phone, 1800);
            map.put("resultMsg", "获取用户手机号成功");
            map.put("phone", phone);
            map.put("tourismUser", tourismUser);
            return AjaxResult.success(map);
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("用户获取手机号失败！");
    }*/

    /**
     * 通过userId查询用户的信息
     * @param userId
     * @return
     */
    /*@Override
    public AjaxResult selectUserByUserId(Integer userId) {
        TourismUser tourismUser = tourismUserMapper.selectByUserId(userId);
        if(tourismUser == null){
            return AjaxResult.error("该用户还未进行注册或登录，请先注册或登录！");
        }
        return AjaxResult.success(tourismUser);
    }*/


}
